<?php
/**
 * Date: 2024.8
 * Author: kahn
 * 基础控制器
 */

use config\Response;
use JetBrains\PhpStorm\NoReturn;

class Controller extends \Yaf_Controller_Abstract {

    protected int $userId;
    protected array $params;
    //类初始化
    public function init(): void
    {
        $this->userId = Yaf_Registry::get('userId');
    }

    /**
     * @param $field
     * @param $type_func
     * @param bool $necessary
     * @param $defaultValue
     * @return mixed|string|void|null
     */
    protected function _getParam($field, $type_func, bool $necessary=true, $defaultValue=null)
    {
        $value = GCommon->$field;
        if($value === null){  //如果参数不存在
            if($necessary){ //如果是必传参数
                $this->_response(Response::PARAMS_LACK, ['msg'=>"$field required"]);
            }else{ //非必传参数
                return $defaultValue ?? null;
            }
        }else{
            if($type_func == 'string'){
                return trim($value);
            }elseif($type_func == "array") {
                return $value;
            }else{
                return call_user_func($type_func, $value);
            }
        }
    }

    /* json返回值 */
    #[NoReturn] protected function _response($code, $data=NUll): void
    {
        response($code, $data);
    }
}
